﻿#region License

/*
    Copyright (c) 2012 Joseph Haluska
    This source is subject to the Microsoft Public License (Ms-PL).
    Please see http://www.microsoft.com/en-us/openness/licenses.aspx for details.
    All other rights reserved.
*/

#endregion License

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace NetExceptionReporter.Utilities
{
    public static class SerializationUtilities
    {
        public static string ToBase64(object obj)
        {
            if (obj == null)
                throw new ArgumentNullException("obj");

            using (MemoryStream memoryStream = new MemoryStream())
            {
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                binaryFormatter.Serialize(memoryStream, obj);
                return Convert.ToBase64String(memoryStream.ToArray());
            }
        }

        public static object FromBase64(string str)
        {
            if (String.IsNullOrEmpty(str))
                throw new ArgumentNullException("str");

            byte[] data = Convert.FromBase64String(str);

            using (MemoryStream memoryStream = new MemoryStream(data))
            {
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                return binaryFormatter.Deserialize(memoryStream);
            }
        }
    }
}